package dao

import (
	"fmt"
	"laohuo/model"
	"time"
)

// FetchSupplier xxx
func FetchSupplier(page, pagesize uint) (model.Suppliers, error) {
	db, err := connect()
	if err != nil {
		return nil, err
	}
	defer db.Close()

	rows, err := db.Query("SELECT * FROM `supplier` WHERE isdel=0 ORDER BY `time` DESC LIMIT ?,?", (page-1)*pagesize, pagesize)
	if err != nil {
		return nil, fmt.Errorf("查询失败: %v", err)
	}
	defer rows.Close()

	var sus model.Suppliers
	for rows.Next() {
		var su model.Supplier
		var isdel uint
		if err := rows.Scan(&su.Id, &su.Name, &su.Address.Country, &su.Address.Province, &su.Address.City, &su.Address.Street,
			&su.Address.Detail, &su.Phone, &su.Email, &su.Status, &su.Time, &isdel); err != nil {
			continue
		}
		sus = append(sus, &su)
	}

	if err := rows.Err(); err != nil {
		return nil, fmt.Errorf("数据解析失败: %v", err)
	}
	return sus, nil
}

// AddSupplier xxx
func AddSupplier(su *model.Supplier) error {
	db, err := connect()
	if err != nil {
		return err
	}
	defer db.Close()

	res, err := db.Exec("INSERT INTO `supplier`(name, country, province, city, street, detail, phone, email, status, time) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
		su.Name, su.Address.Country, su.Address.Province, su.Address.City, su.Address.Street, su.Address.Detail, su.Phone, su.Email, model.Active, time.Now().Unix())
	if err != nil {
		return err
	}
	id, _ := res.LastInsertId()
	su.Id = uint(id)
	return nil
}

//
func UpdateSupplierStatus(id uint, s model.SupplierStatus) error {
	db, err := connect()
	if err != nil {
		return err
	}
	defer db.Close()

	_, err = db.Exec("UPDATE `supplier` SET `status`=? WHERE `id`=?", s, id)
	return err
}

func CountSupplier() (int, error) {
	db, err := connect()
	if err != nil {
		return 0, err
	}
	defer db.Close()

	count := 0
	if err := db.QueryRow("SELECT COUNT(*) FROM `supplier` WHERE `isdel`=0").Scan(&count); err != nil {
		return 0, err
	}
	return count, nil
}
